package com.base.tree;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TreeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Pragma","no-cache");
		response.setContentType("text/xml;charset=utf-8");
		
		String treeId = request.getParameter("treeId");
		if("".equals(treeId)) {
			return ;
		}
		
		String pid = request.getParameter("pid");
		
		Tree tree = TreeManager.getTree(treeId);
		
		PrintWriter out = response.getWriter();
		StringBuffer treeXml = new StringBuffer();  
		
		treeXml.append("<?xml version='1.0' encoding='UTF-8'?>");
		
		treeXml.append("<tree>");
		// 节点html
		String html = tree.view(pid);
		treeXml.append("<html><![CDATA[").append(html).append("]]></html>");
		
		// 节点对象
		treeXml.append("<treeNodes>");
		List<TreeNode> nodes = tree.getNodes(pid);
		for(TreeNode node : nodes) {
			treeXml.append("<treeNode>")
				.append(node.toArgs())
					.append("</treeNode>");
		}
		treeXml.append("</treeNodes>");
		treeXml.append("</tree>");
		
		out.write(treeXml.toString());
		out.flush();
//System.out.println(treeXml);
	}
}